const Promise = require('bluebird');

module.exports = function ({Permissions, sequelize}) {

    /**
     * 检查权限 V2
     */
    Permissions.checkV2 = function ({user_id, permission}) {
        if (!permission) return Promise.resolve({success: true});

        let sql = "select count(*) as count from Permissions p inner join PermissionsRoles pr on(pr.permission_id = p.id) " +
            "where pr.role = (select role from Users where status = 'Active' and id = :user_id) and p.object_type = :object_type and p.action_type = :action_type";

        return sequelize.query(sql, {
            plain: true,
            replacements: {
                user_id: user_id,
                object_type: permission.object_type,
                action_type: permission.action_type
            }
        }).then(function (result) {
            if (result.count > 0) {
                return {success: true}
            } else {
                return {success: false, code: 403, message: '用户没有该权限'};
            }
        });
    }

    /**
     * 查询用户所有的权限 V2
     */
    Permissions.findAllByUserV2 = function ({user_id}) {
        let sql = "select p.object_type, p.action_type from Permissions p inner join PermissionsRoles pr on(pr.permission_id = p.id) " +
            "where pr.role = (select role from Users where status = 'Active' and id = :user_id)";

        return sequelize.query(sql, {
            type: sequelize.QueryTypes.SELECT,
            replacements: {user_id: user_id}
        });
    }

    /**
     * 查找有权限的所有用户编号 V2
     */
    Permissions.findAllUsersV2 = function ({permission}) {
        let sql = "select id from Users where role in (select role from PermissionsRoles " +
            "where permission_id = (select id from Permissions where object_type = :object_type and action_type = :action_type))";

        return sequelize.query(sql, {
            type: sequelize.QueryTypes.SELECT,
            replacements: {
                object_type: permission.object_type,
                action_type: permission.action_type
            }
        });
    }
}